<?php 
	require_once '../function.php';

	$user = xiu_get_current_user_admin();


	// 能获取到ID,说明是修改操作
	if (!empty($_GET['id'])) {
		$id = $_GET['id'];
		$edit_category = xiu_fetch_db_one("select * from categories where id='{$id}'");
	}

	// 新增分类
	function add_category(){
		global $user;

		if (empty($_POST['name'])) {
			$GLOBALS['message_false'] = '请填写分类名称';
			return;
		}
		if (empty($_POST['slug'])) {
			$GLOBALS['message_false'] = '请填写分类别名';
			return;
		}

		$name = $_POST['name'];
		$slug = $_POST['slug'];

		// 查询是否已存在该分类
		$res = xiu_fetch_db_one("select * from categories where name='{$name}' and user_id='{$user['id']}' limit 1;");
		if ($res) {
			$GLOBALS['message_false'] = '该分类已存在,请重新输入';
			return;
		}

		// 插入数据
		$affected_rows = xiu_operation_db("insert into categories values(null, '{$slug}','{$name}','{$user['id']}');");

		echo "insert into categories values(null, '{$slug}','{$name}','{$user['id']}');";

		if ($affected_rows <= 0) {
			$GLOBALS['message_false'] = '添加失败,请稍后重试';
			return;
		}

		$GLOBALS['message_true'] = '添加成功';
		

		header('Location: /admin/categories.php');

	}

	// 修改分类
	function edit_category(){
		//哪里需要使用全局变量,就在哪里声明全局变量
		global $edit_category;

		$name = empty($_POST['name']) ? $edit_category['name'] : $_POST['name'];
		$slug = empty($_POST['slug']) ? $edit_category['slug'] : $_POST['slug'];

		$result = xiu_operation_db("update categories set name='".$name."',slug='".$slug."' where id=".$edit_category['id'].";");

		if( $result < 0){
			$GLOBALS['message_false'] = '更新失败!';
			return;
		}

		header('Location: /admin/categories.php');
	}


	// 如果添加操作和查询操作在一起,那么一定是先添加,后查询,这样才能显示添加后的数据
	if ($_SERVER['REQUEST_METHOD'] === 'POST') {
		// 新增
		if (empty($_GET['id'])) {
			add_category();
		}else{
			// 修改
			edit_category();
		}
		

	}



	//获取分类数据
	$categories = xiu_fetch_db_all("select * from categories where user_id={$user['id']};");
 ?>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>所有分类</title>
	<link rel="stylesheet" type="text/css" href="/static/vendors/bootstrap4.6/css/bootstrap.css">
	<link rel="stylesheet" type="text/css" href="/static/css/admin.css">
</head>
<body>
	<div class="main">
		<?php include './inc/navbar.php' ?>
		<div class="container-fluid">
			<div class="page-title">
				<h1>分类目录</h1>
			</div>
			<div class="row">
				<div class="col-md-4">
					<form action="<?php echo $_SERVER['PHP_SELF'] ?><?php echo isset($edit_category)?'?id='.$edit_category['id']: ''; ?>" method="post">
						<h2><?php echo isset($edit_category)? '修改': '添加' ?>分类</h2>
						<?php if (isset($message_false)): ?>
						<div class="alert alert-danger">
						  <?php echo $message_false; ?>
							</div>
						<?php endif ?>

						<div class="form-group">
							<label for="name">名称</label>
							<input type="text" name="name" id="name" placeholder="分类名称" class="form-control" autocomplete="off" value="<?php echo isset($edit_category) ? $edit_category['name'] : ''; ?>">
						</div>
						<div class="form-group">
							<label form="slug">别名</label>
							<input type="text" name="slug" id="slug" placeholder="别名" class="form-control" autocomplete="off" value="<?php echo isset($edit_category) ? $edit_category['slug'] : ''; ?>">
						</div>
						<div class="form-group">
							<button class="btn btn-primary" class="form-control" type="submit"><?php echo isset($edit_category)? '保存': '添加'; ?></button>
						</div>
					</form>
				</div>
				<div class="col-md-8">
					<a id='categories_delete' class="btn btn-danger btn-sm" href="" style="display: none;">批量删除</a>
					<table class="table table-bordered table-hover">
						<thead>
							<tr>
								<th><input type="checkbox" class="check_all"></th>
								<th>名称</th>
								<th>别名</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
							<?php if ($categories): ?>
								<?php foreach ($categories as $item): ?>
									<tr>
										<!-- 在html5中规定,自定义属性前,必须添加前缀data -->
										<td><input type="checkbox" data-id="<?php echo $item['id']; ?>"></td>
										<td><?php echo $item['name']; ?></td>
										<td><?php echo $item['slug']; ?></td>
										<td>
											<a href="/admin/categories.php?id=<?php echo $item['id']; ?>" class="btn btn-primary btn-sm">编辑</a>
											<a href="/admin/categories-delete.php?id=<?php echo $item['id']; ?>" class="btn btn-danger btn-sm">删除</a>
										</td>
									</tr>
								<?php endforeach ?>
							<?php endif ?>
							<?php if (!$categories): ?>
								<p>还未建立任何分类，赶快新建分类吧~</p>
							<?php endif ?>
							
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>

	<?php $current_page = 'categories' ?>
	<?php include './inc/asid.php'; ?>
	<script src="/static/vendors/jQuery.js"></script>
	<script src="/static/js/aside.js"></script>
	<script type="text/javascript">
		//实现批量删除功能
		$(function(){
			var checkboxs = $('tbody input');
			var categories_delete = $('#categories_delete');
			// 可以使用attr() 和 prop() 方法获取属性
			// attr()获取的是html标签中的属性,返回值是属性值
			// prop()获取的是DOM的属性,返回值是boolean
			// 创建一个数组,存放被选中分类的id
			var checkedId = [];
			// 选中分类,出现批量删除按钮
			checkboxs.on('change', function(){
				// 对于自定义属性,DOM中有一个dataset属性专门存放自定义属性
				var id = $(this).data('id');
				if ($(this).prop('checked')) {
					// 判断当前id是否已经在数组中,如果在就不添加
					checkedId.includes(id) || checkedId.push(id);
				}else{
					// 如果取消选中,则移除数组中的id
					checkedId.splice(checkedId.indexOf(id),1);
				}
				checkedId.length ? categories_delete.fadeIn() : categories_delete.fadeOut();
				categories_delete.attr('href', '/admin/categories-delete.php?id='+checkedId);
			})

			// 点击全选框,选中所有分类
			// $('.check_all').on('change', function(){
			// 	var status = $(this).prop('checked');
			// 	// 将所有分类设置为与.check_all一样的状态
			// 	checkboxs.each(function(index, ele){
			// 		$(ele).prop('checked', status);
			// 	})
			// })


			// 全选和全不选
			$('.check_all').on('change', function(){
				var checked = $(this).prop('checked');
				checkboxs.prop('checked', checked).trigger('change');
			})
		})
	</script>
</body>
</html>